<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px">
          <el-form-item label="课程" prop="courseId">
            <el-input v-model="queryParams.courseId" placeholder="请输入课程" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学段" prop="coursePeriod">
            <!-- <el-input v-model="queryParams.coursePeriod" placeholder="请输入学段" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.coursePeriod" placeholder="请输入学段" clearable>
              <el-option
                v-for="dict in sys_period"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="年级" prop="courseGrade">
            <!-- <el-input v-model="queryParams.courseGrade" placeholder="请输入年级" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.courseGrade" placeholder="请选择学段" clearable>
              <el-option v-for="dict in sys_grade" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="学科" prop="courseSubject">
            <!-- <el-input v-model="queryParams.courseSubject" placeholder="请输入学科" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.courseSubject" clearable placeholder="请选择学科">
              <el-option v-for="dict in subjectOptions" :key="dict.id" :label="dict.subjectName" :value="dict.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="授课教室" prop="courseRoot">
            <el-input v-model="queryParams.courseRoot" placeholder="请输入授课教室" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="授课教师" prop="courseTeacher">
            <!-- <el-input v-model="queryParams.courseTeacher" placeholder="请输入授课教师" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.courseTeacher"  clearable  placeholder="请选择教师" >
              <el-option v-for="dict in teacherOptions" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="授课学校" prop="courseDept">
            <!-- <el-tree-select
            filterable
            clearable
             v-model="queryParams.courseDept"
            :data="deptOptions"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
            value-key="deptId"
            placeholder="请选择学校"
            :render-after-expand="false"
          /> -->
            <el-select v-model="queryParams.courseDept" placeholder="请选择学校" clearable :disabled="!(userId === 1 && tenantDisabled)">
              <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="授课时间" prop="courseDate">
            <el-date-picker clearable
              v-model="queryParams.courseDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择授课时间"
            />
          </el-form-item>
  
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <!-- <el-button type="primary"  @click="handleAdd" v-hasPermi="['core:courseCertificate:add']">新增</el-button> -->
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <h2>开课凭证</h2>
      </template>

      <el-table v-loading="loading" :data="courseCertificateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="课程编号" align="center" prop="id" v-if="true" />
        <el-table-column label="课程" align="center" prop="courseId" />
        <el-table-column label="学段" align="center" prop="coursePeriod" >
        <template #default="scope">
            <dict-tag :options="sys_period" :value="scope.row.coursePeriod"/>
          </template>
        </el-table-column>
        <el-table-column label="年级" align="center" prop="courseGrade" >
          <template #default="scope">
            <dict-tag :options="sys_period" :value="scope.row.courseGrade" />
          </template>
        </el-table-column>
        <el-table-column label="学科" align="center" prop="courseSubject" >
          <template #default="scope">
                 {{ getSubjectNameById(subjectOptions, scope.row.courseSubject) }}
            </template>
        </el-table-column>
        <el-table-column label="授课学校" align="center" prop="courseDept">
          <template #default="scope">
            {{getSchoolById(deptOptions,scope.row.courseDept)}}
          </template>
        </el-table-column>
        <el-table-column label="地区" align="center" prop="" />
        <el-table-column label="授课教室" align="center" prop="courseRoot" />
        <el-table-column label="授课教师" align="center" prop="courseTeacher" >
          <template #default="scope">
                 {{ getTeacherNameById(teacherOptions, scope.row.courseTeacher) }}
            </template>
        </el-table-column>
        <el-table-column label="授课时间" align="center" prop="courseDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.courseDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="凭证状态" align="center" prop="status" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" >
          <template #default="scope">
              <el-button type="text" size="small"  @click="handleDelete(scope.row)" v-hasPermi="['core:courseCertificate:remove']">删除</el-button>
              <el-button type="text" size="small"  @click="handleUpdate(scope.row)" v-hasPermi="['core:courseCertificate:edit']">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改实验课程开课凭证对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="courseCertificateFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="课程" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入课程" />
        </el-form-item>
        <el-form-item label="学段" prop="coursePeriod">
          <el-select v-model="form.coursePeriod" placeholder="请输入学段" clearable>
              <el-option
                v-for="dict in sys_period"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="年级(班级)" prop="courseGrade">
          <el-input v-model="form.courseGrade" placeholder="请输入年级(班级)" />
        </el-form-item>
        <el-form-item label="学科" prop="courseSubject">
          <el-input v-model="form.courseSubject" placeholder="请输入学科" />
        </el-form-item>
        <el-form-item label="授课教室" prop="courseRoot">
          <el-input v-model="form.courseRoot" placeholder="请输入授课教室" />
        </el-form-item>
        <el-form-item label="授课教师" prop="courseTeacher">
          <el-input v-model="form.courseTeacher" placeholder="请输入授课教师" />
        </el-form-item>
        <el-form-item label="授课学校" prop="courseDept">
          <el-tree-select
          filterable
            clearable
            v-model="form.courseDept"
            :data="deptOptions"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
            value-key="deptId"
            placeholder="请选择学校"
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="授课时间" prop="courseDate">
          <el-date-picker clearable
            v-model="form.courseDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择授课时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="凭证状态" prop="status">
          <el-input v-model="form.status" placeholder="凭证状态" />
        </el-form-item>
        <el-form-item label="开课集体照" prop="groupPhoto">
          <imageUpload v-model="form.groupPhoto"  :isShowTip="false" class="imgView-box"/>
        </el-form-item>
        <el-form-item label="开课课程照" prop="coursePhoto">
          <imageUpload v-model="form.coursePhoto"  :isShowTip="false" class="imgView-box" />
        </el-form-item>
        <el-form-item label="开课课程照" prop="studentPhoto">
          <imageUpload v-model="form.studentPhoto"  :isShowTip="false" class="imgView-box" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CourseCertificate" lang="ts">
import { listDept } from "@/api/system/dept"; //学校
import { DeptVO } from "@/api/system/dept/types"; //学校
import { listCourseCertificate, getCourseCertificate, delCourseCertificate, addCourseCertificate, updateCourseCertificate } from '@/api/core/courseCertificate';
import { CourseCertificateVO, CourseCertificateQuery, CourseCertificateForm } from '@/api/core/courseCertificate/types';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_notice_type, sys_period,sys_grade } = toRefs<any>(proxy?.useDict('sys_notice_type', 'sys_period','sys_grade'));


/** 公共方法 */ 
import { getSubjectNameById,getTeacherNameById,getSchoolById } from '@/utils/index';
import { useSubjectList } from '@/composables/useSubjectList';
const { subjectOptions, fetchSubjectList } = useSubjectList();
import { useTeacherList} from '@/composables/useSubjectList';
const { teacherOptions, fetchTeacherList } = useTeacherList();
//学校改租户数据
import { useTenantlList } from '@/composables/useSchoolList';
const { tenantOptions, fetchTenantlList, tenantDisabled} = useTenantlList();
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantId = ref(userStore.tenantId)
/** 公共方法end */ 
const courseCertificateList = ref<CourseCertificateVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const courseCertificateFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 学校
interface DeptOptionsType {
  deptId: number | string;
  deptName: string;
  children: DeptOptionsType[];
}
const deptOptions = ref<DeptOptionsType[]>([]); //学校

const initFormData: CourseCertificateForm = {
  courseId: undefined,
  coursePeriod: undefined,
  courseGrade: undefined,
  courseSubject: undefined,
  courseRoot: undefined,
  courseTeacher: undefined,
  courseDept: undefined,
  courseDate: undefined,
  groupPhoto: undefined,
  coursePhoto: undefined,
  studentPhoto: undefined,
  status: undefined,
}
const data = reactive<PageData<CourseCertificateForm, CourseCertificateQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    courseId: undefined,
    coursePeriod: undefined,
    courseGrade: undefined,
    courseSubject: undefined,
    courseRoot: undefined,
    courseTeacher: undefined,
    courseDept: undefined,
    courseDate: undefined,
    groupPhoto: undefined,
    coursePhoto: undefined,
    studentPhoto: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    courseId: [
      { required: true, message: "课程不能为空", trigger: "blur" }
    ],
    coursePeriod: [
      { required: true, message: "学段不能为空", trigger: "blur" }
    ],
    courseGrade: [
      { required: true, message: "年级(班级)不能为空", trigger: "blur" }
    ],
    courseSubject: [
      { required: true, message: "学科不能为空", trigger: "blur" }
    ],
    courseRoot: [
      { required: true, message: "授课教室不能为空", trigger: "blur" }
    ],
    courseTeacher: [
      { required: true, message: "授课教师不能为空", trigger: "blur" }
    ],
    courseDept: [
      { required: true, message: "授课学校不能为空", trigger: "change" }
    ],
    courseDate: [
      { required: true, message: "授课时间不能为空", trigger: "blur" }
    ],
    groupPhoto: [
      { required: true, message: "开课集体照不能为空", trigger: "blur" }
    ],
    coursePhoto: [
      { required: true, message: "开课课程照不能为空", trigger: "blur" }
    ],
    studentPhoto: [
      { required: true, message: "开课课程照不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "凭证状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学校列表 */
const getSchoolList = async () => {
  const res = await listDept();
  const data = proxy?.handleTree<DeptOptionsType>(res.data, "deptId");
  if (data) {
    deptOptions.value = data;
  }
};

/** 查询实验课程开课凭证列表 */
const getList = async () => {
  courseCertificateList.value=[{
    id:1,
    courseId: 1,
  coursePeriod: 1,
  courseGrade: 1,
  courseSubject: 1,
  courseRoot: 1,
  courseTeacher: 1,
  courseDept: 1,
  courseDate: 1,
  groupPhoto: 1,
  coursePhoto: 1,
  studentPhoto: 1,
  status: 1,
  }]
   
  // loading.value = true;
  // const res = await listCourseCertificate(queryParams.value);
  // courseCertificateList.value = res.rows;
  // total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  courseCertificateFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: CourseCertificateVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// /** 新增按钮操作 */
// const handleAdd = () => {
//   reset();
//   dialog.visible = true;
//   dialog.title = "添加实验课程开课凭证";
// }

/** 修改按钮操作 */
const handleUpdate = async (row?: CourseCertificateVO) => {
    const _id = row?.id || ids.value[0]
  router.push({ path: '/open/courseCertificate/panel/', query: { id: _id, } });
 
  // reset();
  // const _id = row?.id || ids.value[0]
  // // const res = await getCourseCertificate(_id);
  // // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = "修改实验课程开课凭证";
}

/** 提交按钮 */
const submitForm = () => {
  courseCertificateFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateCourseCertificate(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addCourseCertificate(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: CourseCertificateVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除实验课程开课凭证编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delCourseCertificate(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('core/courseCertificate/export', {
    ...queryParams.value
  }, `courseCertificate_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  if(!(userId.value === 1 && tenantDisabled.value)){
    queryParams.value.courseDept = Number(tenantId.value) ;
  }
  getList();
  getSchoolList()
});
</script>
